import { without } from 'lodash'
import Resources from './resources'
const _resources = new Resources()

setInterval(()=>{
    console.log(_resources.getType())
},5000)

export default io => {
    io.on('connection', socket => {

        socket.on('join', room => {
            //加入房间  用来区分不同资源
            socket.join(room, () => {

                io.to(room).clients((err, clients) => {
                    //返回已加入房间通知
                    console.log(clients);
                    socket.emit('ready', {
                        success: true
                    });
                });

                //提交资源
                socket.on('addPart', (videoid, resource, type) => {
                    _resources.add(socket.id, videoid, resource, type)                 
                });

                //失联
                socket.on('disconnect', () => {
                    _resources.delete(socket.id);
                });


                socket.on('getPeer', (videoid, part) => {
                    let peer = {
                        part: part,
                        resources: without(_resources.get(videoid, part), socket.id)
                    };
                    
                    console.log(peer);
                    socket.emit('returnPeer', peer);
                });
            });
        });


        //signaling 一部分
        socket.on('sendCandidate', (id, candidate) => {
            socket.to(id).emit('receiveCandidate', socket.id, candidate);
        });
        //signaling 一部分
        socket.on('sendOffer', (id, offer) => {
            socket.to(id).emit('receiveOffer', socket.id, offer);
        })
        //signaling 一部分
        socket.on('sendAnswer', (id, answer) => {
            socket.to(id).emit('receiveAnswer', socket.id, answer);
        })
    })
}